package com.example.mail.productservice.rest;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.account.feign.AccountFeign;
import com.example.product.dto.ProductDTO;
import com.example.rest.RestBody;
import com.example.rest.RestCode;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.example.mail.productservice.service.ProductService;

import com.example.mail.productservice.entity.Product;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhou
 * @since 2022-01-10
 */
@AllArgsConstructor
@RestController
@RequestMapping("/product")
public class ProductController {

    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    private final ProductService productService;
    private final AccountFeign accountFeign;

    /**
     * 分页查询 Product 对象
     * @return Rest
     */
    @GetMapping("/{code}")
    @SentinelResource(value = "/product/getByCode", fallback = "fallback")
    public RestBody<?> list(@PathVariable("code")String code){

        if("bala".equals(code)){
            throw new RuntimeException("error");
        }
        Product one = this.productService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getProductCode,code)
        );
        return RestBody.ok(one);/*this.accountFeign.getByCode(code);*/
    }

    public RestBody<?> fallback(String code){
        logger.info("服务已熔断：{}", code);
        return RestBody.fail(RestCode.DEGRADE);
    }

    @PostMapping("/reduce/store")
    public RestBody<?> reduceProductStore(@RequestBody ProductDTO productDTO){
        String code = productDTO.getCode();
        Product one = this.productService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getProductCode, code));
        if(one != null && one.getCount() > 0){
            one.setCount(one.getCount() - productDTO.getNum());
            this.productService.updateById(one);
            return RestBody.ok();
        }
        throw new RuntimeException("no such product or product store not enough");
    }
    /**
     * 新增或修改 Product 实体接口
     * @return Rest
     */
    @PostMapping
    public RestBody<?> createOrUpdate(@Valid @RequestBody Product product){
        //Product product = ProductConverter.INSTANCE.toProduct(productDTO);

        if(product.getId() != null){
            this.productService.updateById(product);
        }else{
            this.productService.save(product);
        }
        return RestBody.ok();
    }

    /**
     * 逻辑删除一条 实体，
     * 注意当且仅当调用 mybatis plus 内置方法时可以自动处理
     * @param id 资源对应id主键
     * @return Rest
     */
    @DeleteMapping("/{id}")
    public RestBody<?> delete(@PathVariable("id")  Long id){
        boolean removed = this.productService.removeById(id);
        //Restful风格建议，无可操作数据时，返回404资源未找到提示
        return removed ? RestBody.ok() : RestBody.fail(RestCode.RESOURCE_NOT_FOUND);
    }

}

